package com.yld.car.market;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import cn.yld.car.db.RecentlyViewedDBHelper;

import com.androidquery.AQuery;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.bitmap.BitmapDisplayConfig;
import com.lidroid.xutils.bitmap.core.BitmapSize;
import com.yld.car.common.ConstantUtils;
import com.yld.car.common.NetworkProgressUtils;
import com.yld.car.domain.DealerBaseInfo;
import com.yld.car.domain.FilterCarInfo;
import com.yld.car.domain.SearchDetailCar;
import com.yld.car.domain.UserInfo;

public class DealerHomePageActivity extends BaseActivity implements
		OnItemClickListener {

	private Button rightButton;
	private Button modelButton;

	private ListView carTypeList;

	private ListView list2;
	private String id;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		// 去掉标题栏
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.dealer_home_page);
		initViews();
		Intent i = getIntent();
		mBar = (ProgressBar) findViewById(R.id.progressBar);
		String name = i.getStringExtra("name");
		id = i.getStringExtra("carId");
		id = "1";

		utils = NetworkProgressUtils.getInstance();
		super.onCreate(savedInstanceState);

		carTypeList = (ListView) findViewById(R.id.list1);
		carTypeList.setOnItemClickListener(this);
		list2 = (ListView) findViewById(R.id.list2);

		TopItemAdapter topItemAdapter = new TopItemAdapter();
		list2.setAdapter(topItemAdapter);
		list2.setOnItemClickListener(topItemListener);
		// showButton();

		carTypeList.setOnItemClickListener(this);
		// new CarTypeTask().execute(new String[] { "8", "", "" });

	}

	private ProgressBar mBar;
	private View.OnClickListener filterOnClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {

			Intent intent = new Intent();
			intent.setClass(DealerHomePageActivity.this,
					FilterTypeActivity.class);
			startActivityForResult(intent, 1);

		}
	};

	private void showButton() {

		Button localButton = (Button) findViewById(R.id.leftButton);
		localButton.setVisibility(View.VISIBLE);

		localButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				finish();

			}
		});
	}

	private NetworkProgressUtils utils;

	private class DealerAttentionTask extends
			AsyncTask<String, String, ArrayList<DealerBaseInfo>> {

		@Override
		protected ArrayList<DealerBaseInfo> doInBackground(String... params) {

			/*
			 * GetDealersByKeyWords(string userId,string city, string port,
			 * string pageIndex, string pageSize)
			 * 
			 * 参数一：userId:当前登录的用户编号 参数一：city:城市，（和注册功能中的省市一样的，但是这里只绑定省/市， 不要市/县）
			 * 
			 * 参数二：port:港口，（找经销商页面顶部的“港口”按钮，绑定港口的方法“GetCarAllPorts（）”见第一版接口说明书）
			 * 
			 * 参数三：nowPage:当前页码，（数参数值例如：“1”）
			 * 
			 * 参数四：pageSize:每页显示条数，（参数值例如：“20”）
			 */

			UserInfo u = (UserInfo) readObject("userInfo");
			HashMap<String, String> allParams = new HashMap<String, String>();

			allParams.put("userId", u.getUserId());
			allParams.put("city", params[0]);
			allParams.put("port", params[1]);
			allParams.put("nowPage", "1");
			allParams.put("pageSize", "20");
			Object o = utils.getWebservicesByData(
					ConstantUtils.NAME_SPACE,
					ConstantUtils.ALL_METHROD_NAME.get(34),
					ConstantUtils.NAME_SPACE
							+ ConstantUtils.ALL_METHROD_NAME.get(34),
					ConstantUtils.GET_DEALERS_BY_KEY_WORDS_URL, allParams);

			System.out.println("dealer:" + o);
			ArrayList<DealerBaseInfo> all = utils.parseDealerAttention(o
					.toString());

			return all;
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			mBar.setVisibility(View.VISIBLE);
			carTypeList.setVisibility(View.GONE);
		}

		@Override
		protected void onPostExecute(ArrayList<DealerBaseInfo> result) {

			super.onPostExecute(result);

			mBar.setVisibility(View.GONE);
			carTypeList.setVisibility(View.VISIBLE);
			if (result != null) {

				DealerAttentionAdapter adapter = new DealerAttentionAdapter(
						result);
				carTypeList.setAdapter(adapter);
			}
		}

	}

	@Override
	public void onItemClick(AdapterView<?> adapterView, View v, int position,
			long id) {

		Object o = adapterView.getAdapter().getItem(position);

		DealerBaseInfo d = (DealerBaseInfo) o;
		Intent intent = new Intent();
		intent.setClass(this, DealerMarketActivity.class);
		intent.putExtra("bId", d.getId());
		startActivity(intent);
		// Object o = adapterView.getAdapter().getItem(position);
		//
		// if (o instanceof SearchDetailCar) {
		//
		// final SearchDetailCar s = (SearchDetailCar) o;
		// new Thread(new Runnable() {
		//
		// /**
		// * { "recordcount":"1", --返回的数据条数 "table": [ { "no":"1", --序列号
		// * "id": "1683", --车辆ID "name": "外白内黑棕", --车辆外饰内饰简称，即这辆车的标题
		// * "classid": "111", --系列ID "press": "115", --价格（单位W） "qhtime":
		// * "2014-04-30", --到港时间（期货才有时间，现货没有时间即为空） "vin": "", --就是车架号
		// * "xppz": "运动包¤扩展真皮内饰¤红卡钳", --选配配置 "companyname": "",
		// * --这辆车所属经销商公司名称 "adddate": "2014-04-11 18:19:33", --这辆车的录入时间
		// * "pinpainame": "玛莎拉蒂", --此车品牌名称 "xiliename": "GHIBLI S Q4",
		// * --此车系列名称 "gangkouname": "张家港", --这辆车所属经销商公司所在港口 "xhorqh":
		// * "期货" --期货还是现货 } …… ] }
		// */
		// @Override
		// public void run() {
		// SQLiteDatabase sqLiteDatabase = mApp.getmDbHelper()
		// .getWritableDatabase();
		// ContentValues values = new ContentValues();
		// values.put(RecentlyViewedDBHelper.ID, s.getId());
		// values.put(RecentlyViewedDBHelper.NO, s.getNo());
		// values.put(RecentlyViewedDBHelper.NAME, s.getName());
		// values.put(RecentlyViewedDBHelper.CLASS_ID, s.getClassid());
		// values.put(RecentlyViewedDBHelper.PRESS, s.getPress());
		// values.put(RecentlyViewedDBHelper.QHTIME, s.getQhtime());
		// values.put(RecentlyViewedDBHelper.ADD_DATE, s.getAdddate());
		// values.put(RecentlyViewedDBHelper.XPPZ, s.getXppz());
		// values.put(RecentlyViewedDBHelper.COMPANY_NAME,
		// s.getCompanyname());
		// values.put(RecentlyViewedDBHelper.PIN_PAI_NAME,
		// s.getPinpainame());
		// values.put(RecentlyViewedDBHelper.XI_LIE_NAME,
		// s.getXiliename());
		// values.put(RecentlyViewedDBHelper.GANG_KOU_NAME,
		// s.getGangkouname());
		// values.put(RecentlyViewedDBHelper.XHORQH, s.getXhorgh());
		// long rowId = sqLiteDatabase.insert(
		// RecentlyViewedDBHelper.RECENT_VIEW_TABLE, null,
		// values);
		// if (rowId > 0) {
		// System.out.println("insert------>插入成功。");
		// } else {
		//
		// System.out.println("insert------>插入失败。");
		// }
		//
		// }
		// }).start();
		//
		// String cId = s.getId();
		// Intent intent = new Intent();
		// intent.putExtra("cId", cId);
		// intent.putExtra("carName", s.getPinpainame());
		// intent.putExtra("carType", s.getXhorgh());// 类型
		// intent.putExtra("carSeries", s.getXiliename());
		//
		// intent.setClass(this, CarDetailInfoActivity.class);
		// startActivity(intent);
		// }

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);

		if (1 == requestCode && RESULT_OK == resultCode) {

			FilterCarInfo f = (FilterCarInfo) data
					.getSerializableExtra("filter");

			// System.out.println(s);
			// new CarTypeTask().execute(new String[] { f.color, f.type, f.port
			// });
		}
	}

	private void initViews() {

		final View v1 = findViewById(R.id.city);

		final View v2 = findViewById(R.id.port);

		Button btn1 = (Button) v1.findViewById(R.id.itemContent);
		btn1.setOnClickListener(btn1Listener);
		btn1.setText("城市");
		Button btn2 = (Button) v2.findViewById(R.id.itemContent);
		btn2.setText("港口");
		btn2.setOnClickListener(btn2Listener);

	}

	View.OnClickListener btn1Listener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {

			Intent intent = new Intent();
			intent.setClass(DealerHomePageActivity.this,
					PersonProvinceActivity.class);
			startActivity(intent);

		}
	};
	View.OnClickListener btn2Listener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub

			// System.out.println("onClick===2");
			Intent intent = new Intent();
			intent.setClass(DealerHomePageActivity.this,
					SelectorPortActivity.class);
			String type = mApp.getClassId();
			if (type == null) {
				type = "8";

			}
			intent.putExtra("cId", type);
			startActivity(intent);
		}
	};

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

		String port = mApp.getmPortInfo();

		String province = mApp.getmProvinceInfo();

		if (province == null) {
			province = "";
		}
		if (port == null) {
			port = "";
		}

		new DealerAttentionTask().execute(new String[] { province, port });
	}

	@Override
	public void finish() {
		// TODO Auto-generated method stub
		super.finish();
		mApp.setmPortInfo(null);

		mApp.setmProvinceInfo(null);
	}

	private class TopItemAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return 2;
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			if (convertView == null) {

				convertView = LayoutInflater.from(getApplicationContext())
						.inflate(R.layout.dealer_top_item, null);
			}

			TextView tv = (TextView) convertView.findViewById(R.id.itemTitle);
			ImageView image = (ImageView) convertView
					.findViewById(R.id.imageView1);
			tv.setTextColor(Color.BLACK);
			if (position == 0) {
				tv.setText("我关注的经销商");
				image.setImageResource(R.drawable.my_attention_dealer);
			}
			if (position == 1) {
				tv.setText("经销商列表");
				image.setImageResource(R.drawable.dealer_list_icon);
			}

			return convertView;
		}

	}

	private class DealerAttentionAdapter extends BaseAdapter {

		public DealerAttentionAdapter(ArrayList<DealerBaseInfo> infos) {
			this.mDealerBaseInfos = infos;
		}

		private ArrayList<DealerBaseInfo> mDealerBaseInfos;

		@Override
		public int getCount() {

			return mDealerBaseInfos.size();
		}

		@Override
		public Object getItem(int position) {

			return mDealerBaseInfos.get(position);
		}

		@Override
		public long getItemId(int position) {

			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			if (convertView == null) {
				convertView = LayoutInflater.from(DealerHomePageActivity.this)
						.inflate(R.layout.dealer_attention_item, null);

			}

			ImageView imageView = (ImageView) convertView
					.findViewById(R.id.itemCarImage);
			final DealerBaseInfo d = mDealerBaseInfos.get(position);
			String s = d.getUserimg();
			String downloadUrl = null;
			AQuery aq = new AQuery(DealerHomePageActivity.this);
			if (!s.equals("")) {

				if (s.indexOf("aodi") >= 0) {
					downloadUrl = ConstantUtils.DOWNLOAD_IMAGE_URL_NEW;
				} else {
					downloadUrl = ConstantUtils.DOWNLOAD_IMAGE_URL;
				}
				String imgUploadPath = downloadUrl + d.getUserimg();

				aq.id(imageView).image(imgUploadPath, true, true, 0, 0, null,
						0, 1.0f / 1.0f);
				// BitmapUtils bitmapUtils = new BitmapUtils(
				// getApplicationContext());
				//
				// // bitmapUtils.clearCache();
				// bitmapUtils.closeCache();
				// bitmapUtils.supportResume();
				// BitmapDisplayConfig bdc = new BitmapDisplayConfig();
				// bdc.setBitmapMaxSize(new BitmapSize(72, 72));
				// bitmapUtils.display(imageView, imgUploadPath, bdc);
				// 加载网络图片
				// bitmapUtils.display(imageView, imgUploadPath);

			} else {
				// aq.id(imageView).image("assets/splsh1.jpg", true, true, 0, 0,
				// null, 0, 1.0f / 1.0f);
				// imageView.setImageResource(R.drawable.splash1);
			}

			TextView itemText1 = (TextView) convertView
					.findViewById(R.id.dealerItem1);
			itemText1.setText(d.getCompname());

			TextView itemText2 = (TextView) convertView
					.findViewById(R.id.dealerItem2);
			itemText2.setText(d.getComppeople());
			TextView itemText3 = (TextView) convertView
					.findViewById(R.id.dealerItem3);
			itemText3.setText(d.getTelephone());
			TextView itemText4 = (TextView) convertView
					.findViewById(R.id.dealerItem4);
			itemText4.setText(d.getAddress());
			Button button = (Button) convertView
					.findViewById(R.id.attentionBtn);

			UserInfo u = (UserInfo) readObject("userInfo");
			final boolean isMySelf = d.getId().equals(u.getUserId());
			button.setBackgroundResource(R.drawable.dynamic_bg);
			button.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {

					if (isMySelf) {
						Toast.makeText(DealerHomePageActivity.this, "不能关注自己！",
								Toast.LENGTH_SHORT).show();
						return;
					}
					new Thread(new Runnable() {

						@Override
						public void run() {
							UserInfo u = (UserInfo) readObject("userInfo");

							String currentDealerId = u.getUserId();
							String toDealerId = d.getId();

							System.out.println("currentDealerId==>"
									+ currentDealerId + ",toDealerId==="
									+ toDealerId);
							HashMap<String, String> allParams = new HashMap<String, String>();

							allParams.put("fromDealersId", currentDealerId);
							allParams.put("toDealersId", toDealerId);

							Object o = utils.getWebservicesByData(
									ConstantUtils.NAME_SPACE,
									ConstantUtils.ALL_METHROD_NAME.get(36),
									ConstantUtils.NAME_SPACE
											+ ConstantUtils.ALL_METHROD_NAME
													.get(36),
									ConstantUtils.ATTENTION_TO_DEALERS_URL,
									allParams);

							Message msg = mHandler.obtainMessage();

							msg.obj = o;
							// System.out.println("msg------->" + o);
							mHandler.sendMessage(msg);
							
							settingAttentionDealerTags(toDealerId);
						}
					}).start();

				}
			});
			convertView
					.setBackgroundResource(android.R.drawable.list_selector_background);
			return convertView;
		}
	}

	private Handler mHandler = new Handler() {

		public void handleMessage(android.os.Message msg) {

			String m = msg.obj.toString();
			if (m != null && (m.indexOf("操作成功") >= 0)) {
				Toast.makeText(getApplicationContext(), "已成功收录到您关注的经销商列表",
						Toast.LENGTH_SHORT).show();
				String port = mApp.getmPortInfo();

				String province = mApp.getmProvinceInfo();

				if (province == null) {
					province = "";
				}
				if (port == null) {
					port = "";
				}
				new DealerAttentionTask()
						.execute(new String[] { province, port });
			}

		}
	};
	private OnItemClickListener topItemListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> adapterView, View v,
				int position, long id) {

			if (position == 0) {

				Intent intent = new Intent();
				intent.setClass(DealerHomePageActivity.this,
						MySelfAttentionDealerPageActivity.class);
				startActivity(intent);

			}

		}
	};
	
	
	
	
	private void settingAttentionDealerTags(String toDealerId){
		
		
		HashMap<String, String> allParams = new HashMap<String, String>();

		allParams.put("userId", toDealerId);

		NetworkProgressUtils utils = NetworkProgressUtils.getInstance();

		Object o = utils.getWebservicesByData(ConstantUtils.NAME_SPACE,
				ConstantUtils.ALL_METHROD_NAME.get(50),
				ConstantUtils.NAME_SPACE
						+ ConstantUtils.ALL_METHROD_NAME.get(50),
				ConstantUtils.SEND_MESSAGE_FOR_ANDROID_TO_BUTTON_URL,
				allParams);
		int index = o.toString().indexOf("获取别名成功，别名为:");
		
		if (index >= 0) {

			String replace = o.toString().substring(index + 11,
					o.toString().length() - 2);

			
			String alias[] = replace.split(",");

			Set<String> tags=new HashSet<String>();
			
			for (String string : alias) {
				System.out.println("string----"+string);
				tags.add(string);
			}
			JPushInterface.setTags(getApplicationContext(), tags, mAliasCallback);
		}
		
	}
	private void bindAliasPushMsg() {

		new Thread(new Runnable() {

			@Override
			public void run() {

				UserInfo u = (UserInfo) readObject("userInfo");

				String currentDealerId = u.getUserId();

				HashMap<String, String> allParams = new HashMap<String, String>();

				allParams.put("userId", currentDealerId);

				NetworkProgressUtils utils = NetworkProgressUtils.getInstance();

				Object o = utils.getWebservicesByData(ConstantUtils.NAME_SPACE,
						ConstantUtils.ALL_METHROD_NAME.get(50),
						ConstantUtils.NAME_SPACE
								+ ConstantUtils.ALL_METHROD_NAME.get(50),
						ConstantUtils.SEND_MESSAGE_FOR_ANDROID_TO_BUTTON_URL,
						allParams);

				// System.out.println("send--->"+o);
				int index = o.toString().indexOf("获取别名成功，别名为:");
				if (index >= 0) {

					String replace = o.toString().substring(index + 11,
							o.toString().length() - 2);

					System.out.println("");
					String alias[] = replace.split(",");
					
					Set<String> tags=new HashSet<String>();
					
					for (String string : alias) {
						tags.add(string);
					}
					
				/*	for (int i = 0; i < alias.length; i++) {
						// 注册别名时10s内只能注册三个，因此要休眠
						if (i > 0 && (i % 3 == 0)) {
							try {
								Thread.sleep(11000);
							} catch (InterruptedException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}*/
						// JPushInterface.setAliasAndTags(getApplicationContext(),
						// alias[i], null, mAliasCallback);

						//JPushInterface.setTags(getApplicationContext(),
								//alias[i], mAliasCallback);
					JPushInterface.setTags(getApplicationContext(), tags, mAliasCallback);
					
					//}

					allParams = new HashMap<String, String>();

					allParams.put("alias", replace);

					o = utils.getWebservicesByData(ConstantUtils.NAME_SPACE,
							ConstantUtils.ALL_METHROD_NAME.get(51),
							ConstantUtils.NAME_SPACE
									+ ConstantUtils.ALL_METHROD_NAME.get(51),
							ConstantUtils.SEND_MESSAGE_FOR_ANDROID_URL,
							allParams);

					System.out.println(o);
				}
			}
		}).start();

	}
	
	private static final String TAG=DealerHomePageActivity.class.getName();
	private final TagAliasCallback mAliasCallback = new TagAliasCallback() {

		@Override
		public void gotResult(int code, final String alias, Set<String> tags) {
			String logs;
			switch (code) {
			case 0:
				logs = "Set tag and alias success" + tags;
				Log.i(TAG, logs);
				break;

			case 6002:
				logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
				Log.i(TAG, logs);
				if (NetworkProgressUtils.getInstance().getAPNType(
						getApplicationContext()) != -1) {

					new Thread(new Runnable() {
						public void run() {
							JPushInterface.setAliasAndTags(
									getApplicationContext(), alias, null,
									mAliasCallback);
						}
					}).start();
				} else {
					Log.i(TAG, "No network");
				}
				break;

			default:
				logs = "Failed with errorCode = " + code;
				Log.e(TAG, logs);
			}

			// ExampleUtil.showToast(logs, getApplicationContext());
		}

	};
}
